{% extends "base.html" %}

{% block title %}预约日历 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}预约日历{% endblock %}

{% block extra_css %}
<style>
    .calendar-container {
        background: white;
        border-radius: 12px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        overflow: hidden;
    }

    .calendar-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        text-align: center;
    }

    .calendar-nav {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
    }

    .calendar-title {
        font-size: 1.5rem;
        font-weight: 600;
    }

    .nav-btn {
        background: rgba(255,255,255,0.2);
        border: none;
        color: white;
        padding: 8px 12px;
        border-radius: 6px;
        cursor: pointer;
        transition: background 0.2s;
    }

    .nav-btn:hover {
        background: rgba(255,255,255,0.3);
    }

    .calendar-grid {
        display: grid;
        grid-template-columns: repeat(7, 1fr);
        gap: 1px;
        background: #e9ecef;
    }

    .calendar-day-header {
        background: #f8f9fa;
        padding: 15px 5px;
        text-align: center;
        font-weight: 600;
        color: #495057;
        font-size: 0.9rem;
    }

    .calendar-day {
        background: white;
        min-height: 120px;
        padding: 8px;
        position: relative;
        cursor: pointer;
        transition: background 0.2s;
    }

    .calendar-day:hover {
        background: #f8f9ff;
    }

    .calendar-day.other-month {
        background: #f8f9fa;
        color: #6c757d;
    }

    .calendar-day.today {
        background: #e3f2fd;
        border: 2px solid #2196f3;
    }

    .calendar-day.has-reservation {
        background: #fff3e0;
        border-left: 4px solid #ff9800;
    }

    .day-number {
        font-weight: 600;
        margin-bottom: 5px;
        font-size: 0.9rem;
    }

    .reservation-item {
        background: #007bff;
        color: white;
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 0.75rem;
        margin-bottom: 2px;
        display: block;
        text-decoration: none;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .reservation-item:hover {
        background: #0056b3;
        color: white;
        text-decoration: none;
    }

    .reservation-item.status-pending {
        background: #ffc107;
        color: #212529;
    }

    .reservation-item.status-confirmed {
        background: #28a745;
    }

    .reservation-item.status-cancelled {
        background: #dc3545;
    }

    .reservation-item.status-completed {
        background: #6c757d;
    }

    .legend {
        background: white;
        padding: 20px;
        border-top: 1px solid #e9ecef;
    }

    .legend-item {
        display: inline-flex;
        align-items: center;
        margin-right: 20px;
        margin-bottom: 5px;
    }

    .legend-color {
        width: 16px;
        height: 16px;
        border-radius: 4px;
        margin-right: 8px;
    }

    .quick-actions {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .month-stats {
        background: white;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }

    .stat-item {
        text-align: center;
        padding: 15px;
    }

    .stat-number {
        font-size: 1.8rem;
        font-weight: bold;
        color: #007bff;
    }

    .stat-label {
        font-size: 0.9rem;
        color: #6c757d;
        margin-top: 5px;
    }

    .view-toggle {
        background: white;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 20px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        text-align: center;
    }

    .mobile-calendar {
        display: none;
    }

    @media (max-width: 768px) {
        .calendar-grid {
            display: none;
        }

        .mobile-calendar {
            display: block;
            padding: 20px;
        }

        .mobile-day {
            background: white;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .mobile-day.has-reservation {
            border-left: 4px solid #007bff;
        }

        .mobile-day-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 10px;
        }

        .mobile-day-number {
            font-size: 1.2rem;
            font-weight: bold;
        }

        .mobile-day-name {
            color: #6c757d;
            font-size: 0.9rem;
        }
    }

    /* 动画效果 */
    .calendar-day {
        transition: all 0.2s ease;
    }

    .calendar-day:hover {
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    }

    /* 加载状态 */
    .loading {
        opacity: 0.6;
        pointer-events: none;
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 快速操作 -->
    <div class="quick-actions">
        <div class="row align-items-center">
            <div class="col-md-6">
                <h5 class="mb-0">
                    <i class="bi bi-calendar3"></i>
                    预约日历
                </h5>
                <small class="text-muted">查看您的预约安排</small>
            </div>
            <div class="col-md-6 text-end">
                <a href="{{ url_for('student_reservations.create') }}" class="btn btn-primary me-2">
                    <i class="bi bi-plus-circle"></i> 新建预约
                </a>
                <a href="{{ url_for('student_reservations.index') }}" class="btn btn-outline-primary">
                    <i class="bi bi-list"></i> 列表视图
                </a>
            </div>
        </div>
    </div>

    <!-- 月度统计 -->
    <div class="month-stats">
        <div class="row">
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number" id="monthTotal">0</div>
                    <div class="stat-label">本月预约</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number text-success" id="monthConfirmed">0</div>
                    <div class="stat-label">已确认</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number text-warning" id="monthPending">0</div>
                    <div class="stat-label">待确认</div>
                </div>
            </div>
            <div class="col-md-3">
                <div class="stat-item">
                    <div class="stat-number text-info" id="monthCompleted">0</div>
                    <div class="stat-label">已完成</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 日历容器 -->
    <div class="calendar-container">
        <!-- 日历头部 -->
        <div class="calendar-header">
            <div class="calendar-nav">
                <button class="nav-btn" onclick="navigateMonth(-1)">
                    <i class="bi bi-chevron-left"></i>
                </button>
                <div class="calendar-title" id="calendarTitle">
                    {{ current_year }}年{{ current_month }}月
                </div>
                <button class="nav-btn" onclick="navigateMonth(1)">
                    <i class="bi bi-chevron-right"></i>
                </button>
            </div>
            <div class="text-center">
                <button class="nav-btn" onclick="goToToday()">
                    <i class="bi bi-calendar-today"></i> 今天
                </button>
            </div>
        </div>

        <!-- 桌面端日历网格 -->
        <div class="calendar-grid" id="calendarGrid">
            <!-- 星期标题 -->
            <div class="calendar-day-header">日</div>
            <div class="calendar-day-header">一</div>
            <div class="calendar-day-header">二</div>
            <div class="calendar-day-header">三</div>
            <div class="calendar-day-header">四</div>
            <div class="calendar-day-header">五</div>
            <div class="calendar-day-header">六</div>

            <!-- 日期格子将通过JavaScript动态生成 -->
        </div>

        <!-- 移动端日历列表 -->
        <div class="mobile-calendar" id="mobileCalendar">
            <!-- 移动端内容将通过JavaScript动态生成 -->
        </div>

        <!-- 图例 -->
        <div class="legend">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <div class="legend-item">
                        <div class="legend-color" style="background: #ffc107;"></div>
                        <span>待确认</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: #28a745;"></div>
                        <span>已确认</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: #dc3545;"></div>
                        <span>已取消</span>
                    </div>
                    <div class="legend-item">
                        <div class="legend-color" style="background: #6c757d;"></div>
                        <span>已完成</span>
                    </div>
                </div>
                <div class="col-md-4 text-end">
                    <small class="text-muted">
                        <i class="bi bi-info-circle"></i>
                        点击日期可查看详细预约信息
                    </small>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 日期详情模态框 -->
<div class="modal fade" id="dayDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalTitle">预约详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="modalBody">
                <!-- 内容将通过JavaScript填充 -->
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a href="{{ url_for('student_reservations.create') }}" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> 新建预约
                </a>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 日历数据
let calendarData = {{ calendar_data | tojson }};
let currentYear = {{ current_year }};
let currentMonth = {{ current_month }};

// 页面加载完成后初始化日历
document.addEventListener('DOMContentLoaded', function() {
    renderCalendar();
    updateMonthStats();
});

// 渲染日历
function renderCalendar() {
    const grid = document.getElementById('calendarGrid');
    const mobileCalendar = document.getElementById('mobileCalendar');

    // 清除现有内容（保留星期标题）
    const dayHeaders = grid.querySelectorAll('.calendar-day-header');
    grid.innerHTML = '';
    dayHeaders.forEach(header => grid.appendChild(header));
    mobileCalendar.innerHTML = '';

    // 计算月份的第一天和最后一天
    const firstDay = new Date(currentYear, currentMonth - 1, 1);
    const lastDay = new Date(currentYear, currentMonth, 0);
    const startDate = new Date(firstDay);
    startDate.setDate(startDate.getDate() - firstDay.getDay()); // 调整到周日

    const today = new Date();
    const todayStr = formatDate(today);

    // 生成42天的日历格子（6周）
    for (let i = 0; i < 42; i++) {
        const currentDate = new Date(startDate);
        currentDate.setDate(startDate.getDate() + i);

        const dateStr = formatDate(currentDate);
        const dayNumber = currentDate.getDate();
        const isCurrentMonth = currentDate.getMonth() === firstDay.getMonth();
        const isToday = dateStr === todayStr;
        const dayReservations = calendarData[dateStr] || [];

        // 桌面端日历格子
        const dayElement = document.createElement('div');
        dayElement.className = 'calendar-day';

        if (!isCurrentMonth) {
            dayElement.classList.add('other-month');
        }
        if (isToday) {
            dayElement.classList.add('today');
        }
        if (dayReservations.length > 0) {
            dayElement.classList.add('has-reservation');
        }

        dayElement.innerHTML = `
            <div class="day-number">${dayNumber}</div>
            ${dayReservations.map(reservation => `
                <a href="/student-reservations/detail/${reservation.id}" class="reservation-item status-${reservation.status}">
                    ${reservation.start_time.substring(0, 5)} ${reservation.coach.real_name}
                </a>
            `).join('')}
        `;

        dayElement.onclick = () => showDayDetail(dateStr, dayReservations);
        grid.appendChild(dayElement);

        // 移动端日历项目（仅显示当前月份有预约的日期）
        if (isCurrentMonth && dayReservations.length > 0) {
            const mobileDay = document.createElement('div');
            mobileDay.className = 'mobile-day has-reservation';

            mobileDay.innerHTML = `
                <div class="mobile-day-header">
                    <div>
                        <div class="mobile-day-number">${dayNumber}</div>
                        <div class="mobile-day-name">${getDayName(currentDate)}</div>
                    </div>
                    <div class="text-muted">${dayReservations.length}个预约</div>
                </div>
                ${dayReservations.map(reservation => `
                    <div class="reservation-item status-${reservation.status} mb-1 d-block">
                        ${reservation.start_time.substring(0, 5)} - ${reservation.end_time.substring(0, 5)}
                        ${reservation.coach.real_name} (${getStatusDisplayText(reservation.status)})
                    </div>
                `).join('')}
            `;

            mobileCalendar.appendChild(mobileDay);
        }
    }

    // 如果移动端没有预约，显示提示
    if (mobileCalendar.children.length === 0) {
        mobileCalendar.innerHTML = `
            <div class="text-center text-muted py-5">
                <i class="bi bi-calendar-x" style="font-size: 3rem;"></i>
                <h5 class="mt-3">本月暂无预约</h5>
                <p>快去创建您的第一个预约吧！</p>
                <a href="/student-reservations/create" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> 创建预约
                </a>
            </div>
        `;
    }
}

// 格式化日期
function formatDate(date) {
    return date.toISOString().split('T')[0];
}

// 获取星期名称
function getDayName(date) {
    const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return days[date.getDay()];
}

// 显示日期详情
function showDayDetail(dateStr, reservations) {
    const modal = new bootstrap.Modal(document.getElementById('dayDetailModal'));
    const title = document.getElementById('modalTitle');
    const body = document.getElementById('modalBody');

    const date = new Date(dateStr);
    title.textContent = `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 预约详情`;

    if (reservations.length === 0) {
        body.innerHTML = `
            <div class="text-center text-muted py-4">
                <i class="bi bi-calendar-x" style="font-size: 3rem;"></i>
                <h5 class="mt-3">当天暂无预约</h5>
                <p>您可以创建新的预约</p>
            </div>
        `;
    } else {
        body.innerHTML = `
            <div class="list-group">
                ${reservations.map(reservation => `
                    <div class="list-group-item">
                        <div class="d-flex justify-content-between align-items-start">
                            <div class="flex-grow-1">
                                <h6 class="mb-1">
                                    ${reservation.start_time.substring(0, 5)} - ${reservation.end_time.substring(0, 5)}
                                    <span class="badge bg-${getStatusColor(reservation.status)} ms-2">
                                        ${getStatusDisplayText(reservation.status)}
                                    </span>
                                </h6>
                                <p class="mb-1">
                                    <i class="bi bi-person-check"></i> 教练：${reservation.coach.real_name}
                                </p>
                                <p class="mb-1">
                                    <i class="bi bi-grid-3x3"></i> 球台：${reservation.table.name}
                                </p>
                                <small class="text-muted">
                                    <i class="bi bi-currency-dollar"></i> 费用：¥${reservation.price}
                                </small>
                            </div>
                            <div>
                                <a href="/student-reservations/detail/${reservation.id}" class="btn btn-sm btn-outline-primary">
                                    查看详情
                                </a>
                            </div>
                        </div>
                    </div>
                `).join('')}
            </div>
        `;
    }

    modal.show();
}

// 获取状态颜色
function getStatusColor(status) {
    const colors = {
        'pending': 'warning',
        'confirmed': 'success',
        'cancelled': 'danger',
        'completed': 'secondary',
        'no_show': 'dark'
    };
    return colors[status] || 'primary';
}

// 获取状态显示文本
function getStatusDisplayText(status) {
    const statusMap = {
        'pending': '待确认',
        'confirmed': '已确认',
        'cancelled': '已取消',
        'completed': '已完成',
        'no_show': '未到场'
    };
    return statusMap[status] || status;
}

// 月份导航
function navigateMonth(delta) {
    currentMonth += delta;
    if (currentMonth > 12) {
        currentMonth = 1;
        currentYear++;
    } else if (currentMonth < 1) {
        currentMonth = 12;
        currentYear--;
    }

    document.getElementById('calendarTitle').textContent = `${currentYear}年${currentMonth}月`;
    loadCalendarData();
}

// 跳转到今天
function goToToday() {
    const today = new Date();
    currentYear = today.getFullYear();
    currentMonth = today.getMonth() + 1;

    document.getElementById('calendarTitle').textContent = `${currentYear}年${currentMonth}月`;
    loadCalendarData();
}

// 加载日历数据
function loadCalendarData() {
    const grid = document.getElementById('calendarGrid');
    grid.classList.add('loading');

    // 构建URL
    const url = `/student-reservations/calendar?year=${currentYear}&month=${currentMonth}`;

    // 重新加载页面以获取新的数据
    window.location.href = url;
}

// 更新月度统计
function updateMonthStats() {
    let total = 0;
    let confirmed = 0;
    let pending = 0;
    let completed = 0;

    Object.values(calendarData).forEach(dayReservations => {
        dayReservations.forEach(reservation => {
            total++;
            switch (reservation.status) {
                case 'confirmed':
                    confirmed++;
                    break;
                case 'pending':
                    pending++;
                    break;
                case 'completed':
                    completed++;
                    break;
            }
        });
    });

    document.getElementById('monthTotal').textContent = total;
    document.getElementById('monthConfirmed').textContent = confirmed;
    document.getElementById('monthPending').textContent = pending;
    document.getElementById('monthCompleted').textContent = completed;
}

// 响应式处理
function handleResize() {
    const isMobile = window.innerWidth < 768;
    const grid = document.getElementById('calendarGrid');
    const mobile = document.getElementById('mobileCalendar');

    if (isMobile) {
        grid.style.display = 'none';
        mobile.style.display = 'block';
    } else {
        grid.style.display = 'grid';
        mobile.style.display = 'none';
    }
}

// 监听窗口大小变化
window.addEventListener('resize', handleResize);
handleResize(); // 初始检查

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    if (e.ctrlKey || e.metaKey) {
        switch (e.key) {
            case 'ArrowLeft':
                e.preventDefault();
                navigateMonth(-1);
                break;
            case 'ArrowRight':
                e.preventDefault();
                navigateMonth(1);
                break;
            case '.':
                e.preventDefault();
                goToToday();
                break;
        }
    }
});
</script>
{% endblock %}